<template>
    <el-form :model="form" label-width="80px" ref="formRef">
      <el-form-item 
        label="标题" 
        prop="title" 
        :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]"
      >
        <el-input v-model="form.title" placeholder="请输入帖子标题" />
      </el-form-item>
  
      <el-form-item 
        label="内容" 
        prop="content" 
        :rules="[{ required: true, message: '请输入内容', trigger: 'blur' }]"
      >
        <MdEditor v-model="form.content" language="zh-CN" />
      </el-form-item>
  
      <el-form-item label="标签">
        <el-select
          v-model="form.tags"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="选择或输入标签"
          style="width: 100%"
        >
          <el-option
            v-for="tag in commonTags"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
      </el-form-item>
  
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="$emit('cancel')">取消</el-button>
      </el-form-item>
    </el-form>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, watch } from 'vue'
  import { MdEditor } from 'md-editor-v3'
  import 'md-editor-v3/lib/style.css'
  import type { PostVO, PostAddRequest, PostEditRequest } from '../../../generated'
  
  const props = defineProps<{
    post?: PostVO | null
  }>()
  
  const emit = defineEmits<{
    submit: [data: PostAddRequest | PostEditRequest]
    cancel: []
  }>()
  
  const formRef = ref()
  
  const commonTags = ['提问', '分享', '讨论', '求助', '经验', '教程']
  
  const form = reactive<{
    title: string
    content: string
    tags: string[]
  }>({
    title: '',
    content: '',
    tags: [],
  })
  
  // 如果是编辑模式，填充表单
  watch(() => props.post, (post) => {
    if (post) {
      form.title = post.title || ''
      form.content = post.content || ''
      form.tags = post.tagList || []
    } else {
      form.title = ''
      form.content = ''
      form.tags = []
    }
  }, { immediate: true })
  
  const handleSubmit = async () => {
    try {
      await formRef.value?.validate()
      emit('submit', { ...form })
    } catch (e) {
      console.error('表单验证失败', e)
    }
  }
  </script>